package com.tskj.mh.tabletennis.quene;

import com.alibaba.fastjson.JSONObject;
import com.tskj.mh.tabletennis.service.TableTennisService;
import com.tskj.mh.tabletennis.utility.Tools;
import org.springframework.context.ApplicationContext;

/**
 * 羽毛球订单处理线程
 * @author LeonSu
 */
public class TableTennisThread implements Runnable {

    private boolean isQuit;

    private TableTennisQuene tableTennisQuene;
    private TableTennisService tableTennisService;
    private String host;

    public TableTennisThread(ApplicationContext app, String host) {
        this.host = host;
        System.out.println("host=" + host);
        isQuit = false;
        tableTennisQuene = app.getBean(TableTennisQuene.class);
        tableTennisService = app.getBean(TableTennisService.class);
    }

    public void close() {
        isQuit = true;
    }

    @Override
    public void run() {
        System.out.println("订单处理线程开始执行");
        while (!isQuit) {
            try {
                if (tableTennisQuene.size() > 0) {
                    QueneItemInfo info = tableTennisQuene.pop();
                    String userToken = info.getUserToken();
                    JSONObject ret = new JSONObject();
                    try {
                        ret = tableTennisService.saveOrder(info.getStudentInfo(), info.getData());
                    } catch (Exception e) {
                        e.printStackTrace();
                        ret.put("code", 1);
                        ret.put("errMsg", e.getMessage());
                    }

                    JSONObject websocketData = new JSONObject();
                    websocketData.put("code", 0);
                    //后台消息类型是乒乓球
                    websocketData.put("type", 3);
                    websocketData.put("data", ret);

                    JSONObject interfaceData = new JSONObject();
                    interfaceData.put("userToken", userToken);
                    interfaceData.put("data", websocketData);
                    System.out.println(interfaceData.toJSONString());
                    if (!"".equalsIgnoreCase(host)) {
                        Tools.sendPostRequest("http://" + host + "/message/sendMsg.do", interfaceData.toJSONString());
                    } else {
                        Tools.sendPostRequest("http://localhost:8090/message/sendMsg.do", interfaceData.toJSONString());
                    }
                }

                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("订单处理线程结束处理");

    }
}
